package com.zhilianbao.leyaogo.ui.fragment.shoppingcart;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.bql.animationcheckbox.AnimationCheckBox;
import com.bql.convenientlog.CLog;
import com.bql.recyclerview.swipe.SwipeMenu;
import com.bql.recyclerview.swipe.SwipeMenuAdapter;
import com.bql.recyclerview.swipe.SwipeMenuCreator;
import com.bql.recyclerview.swipe.SwipeMenuItem;
import com.bql.statetypelayout.AnimationStateTypeLayout;
import com.bql.utils.AsyncTaskUtils;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.NumberUtlis;
import com.bql.utils.ThreadPool;
import com.google.gson.Gson;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.ActivityApi;
import com.zhilianbao.leyaogo.http.api.OrderApi;
import com.zhilianbao.leyaogo.http.api.ShoppingCartApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.http.callback.LoadingViewCallback;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ActivityFree;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ActivitySubtract;
import com.zhilianbao.leyaogo.model.response.shoppingcart.BaseActivityInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsSKU;
import com.zhilianbao.leyaogo.model.response.shoppingcart.GoodsStock;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShopActivityInfo;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShopActivityList;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShoppingCartGood;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ValidateOrder;
import com.zhilianbao.leyaogo.ui.activity.MainActivity;
import com.zhilianbao.leyaogo.ui.activity.goodscategory.GoodsActivity;
import com.zhilianbao.leyaogo.ui.activity.home.SpecialActivityDetailsActivity;
import com.zhilianbao.leyaogo.ui.activity.shoppingcart.PayOrderActivity;
import com.zhilianbao.leyaogo.ui.adapter.shoppingcart.ShoppingCartAdapter;
import com.zhilianbao.leyaogo.ui.fragment.base.SwipeRefreshAndLoadFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

import static com.bql.convenientlog.CLog.i;

/**
 * Author: hcy
 * Description:购物车Fragment
 * Created: 2016/10/23 15:10
 */
public class ShoppingCartFragment extends SwipeRefreshAndLoadFragment<ShoppingCartGood> implements ShoppingCartAdapter.CheckChangeListener, ShoppingCartAdapter.OnNumChangeListener {

    public static final int STATE_USEABLE = 1, STATE_OUT_STOCK = 2, STATE_NOT_ENOUGH = 3, STATE_DEL = 4;//可购买，下架，库存0，删除；
    public static final int TYPE_GOOD = 1, TYPE_ACTIVITY_TITLE = 2, TYPE_GOOD_ACTIVITY = 3, TYPE_GOOD_UNUSEABLE = 4;
    //商品，活动标题，活动商品与正常商品间隔，正常商品与失效商品间隔
    public static final int SALE = 1, NEW = 2, FREE = 3, SUBTRACT = 4;//活动类型

    @BindView(R.id.tv_calculate)
    TextView calculateTv;

    @BindView(R.id.tv_coupon_price)
    TextView mCouponPriceTv;

    @BindView(R.id.bottom_view)
    public View mBottomView;

    @BindView(R.id.line)
    View mBottomLine;

    @BindView(R.id.tv_total_money)
    public MoneyTextView mTotalMoneyTv;

    @BindView(R.id.checkbox)
    public AnimationCheckBox mCheckBox;

    @BindView(R.id.stateLayout)
    AnimationStateTypeLayout mStateTypeLayout;

    private LoadingViewCallback mCallback;
    private boolean isAllSelect;//是否全选
    private boolean adapterChangeState;//是否由adapter引起的变化
    private boolean isFirstLoad = true, mIsPullToRefresh;//是否是第一次请求,是否是下来刷新

    private CommonDialog mDelDialog;//确定是否删除弹框
    private ShoppingCartAdapter mShoppingCartAdapter;

    //    private double mTotalPrice;
    private int addPosition;//记录添加
    private List<Long> mUnCheckIdList = new ArrayList<>();//未选中的商品id
    private List<ShoppingCartGood> mListData = new ArrayList<>();//重新计算的商品数据
    private List<ShoppingCartGood> mListDataFix = new ArrayList<>();//有效商品商品固定数据
    private List<ShoppingCartGood> mUseList = new ArrayList<>();//可以选择的商品数据，进行筛选操作
    private List<ShoppingCartGood> mUnUsedList = new ArrayList<>();//不可以选中的商品
    private List<ShoppingCartGood> mCheckList = new ArrayList<>();//选中的商品

    private LongSparseArray<List<ShoppingCartGood>> mActivityGoodsArray = new LongSparseArray<>();//满足活动商品list，活动id为key
    private ActivityDiscount mActivityDiscount;//计算活动抵扣价格,是否满包邮
    private List<ShopActivityInfo> mActivityInfoList = new ArrayList<>();//活动列表
    private double shopFreePrice;//店铺活动包邮价格（大于0有效）
    private String shopIds;//去重的所有店铺id
    private int cartCount;//购物车数量
    private boolean isShowBack;

    public static ShoppingCartFragment newInstance(boolean showBackImg) {
        ShoppingCartFragment fragment = new ShoppingCartFragment();
        Bundle bundle = new Bundle();
        bundle.putBoolean("showBack", showBackImg);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onRcvItemClick(RecyclerView.ViewHolder holder, int position) {

        ShoppingCartGood cartGood = mList.get(position);
        Bundle bundle = new Bundle();
        switch (cartGood.getType()) {
            case TYPE_GOOD:
                bundle.putInt(IntentConfig.BUNDLE_GOODS_ID, (int) cartGood.getGoodsId());
                bundle.putInt(IntentConfig.BUNDLE_GOODS_SKU_ID, (int) Utils.getSKUId(cartGood));
                bundle.putBoolean(IntentConfig.IS_FROM_SHOPPING_CART, true);
                Utils.startActivity(mActivity, GoodsActivity.class, bundle);
                break;
            case TYPE_ACTIVITY_TITLE:
                bundle.putLong(IntentConfig.ACTIVITY_ID, cartGood.getActivityId());
                bundle.putBoolean(IntentConfig.IS_FROM_SHOPPING_CART, true);
                Utils.startActivity(mActivity, SpecialActivityDetailsActivity.class, bundle);
                break;
        }

    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_shopping_cart;
    }

    @Override
    public SwipeMenuAdapter getAdapter() {
        return mShoppingCartAdapter;
    }

    @Override
    public RecyclerView.ItemDecoration getItemDecoration() {
        return null;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(mActivity);
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getResources().getString(R.string.shopping_cart));
        isShowBack = getArguments().getBoolean("showBack", false);
        if (!isShowBack) {
            invisibleLeftDrawable();
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mActivity instanceof MainActivity)
            outState.putInt("currentPos", ((MainActivity) mActivity).getCurrentTab());
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (mActivity instanceof MainActivity) {
            if (savedInstanceState != null && savedInstanceState.getInt("currentPos", 0) == 3)
                initLazyViewsAndEvents(savedInstanceState);
        }

    }


    @Override
    protected boolean lazyLoadMode() {
        return !isShowBack;
    }

    @Override
    protected void initLazyViews(@Nullable Bundle savedInstanceState) {
        super.initLazyViews(savedInstanceState);
        if (!isShowBack) {
            init();
        }

    }

    /**
     * 初始化数据
     */
    public void init() {
        CLog.e("init===========================================================================");
        mShoppingCartAdapter = new ShoppingCartAdapter(mActivity, mList);
        mShoppingCartAdapter.setCheckChangeListener(this);
        mShoppingCartAdapter.setOnNumChangeListener(this);
        setAdapterNumClickable();

        mRcvLoadMoreSwipe.setHideLoadingView(true);
        mRcvLoadMoreSwipe.setCanLoadMore(false);
        mCheckBox.setOnCheckedChangeListener(new AnimationCheckBox.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(AnimationCheckBox checkBox, boolean isChecked) {
                if (adapterChangeState) {//如果是Adapter引起的变化不需要改变
                    adapterChangeState = false;//重置
                } else {
                    isAllSelect = isChecked;
                    changeListDataSelectState();
                    mShoppingCartAdapter.setAllSelectChange();
                }
            }
        });
    }

    /**
     * 获取选中商品的记录
     */
    private void getRecordGoodId() {
        List<Long> list = Utils.getShoppingCartUnCheckId();//获取保存的选中商品id
        mUnCheckIdList.clear();
        if (list != null) {
            mUnCheckIdList.addAll(list);
        }
        //        for (Long id : mUnCheckIdList) {
        //            CLog.i("hcy", "mCheckIdList id= " + id);
        //        }
    }

    /**
     * 如果是懒加载 该方法用不到
     *
     * @param savedInstanceState
     */
    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        if (isShowBack) {
            init();
        }

    }

    @Override
    public SwipeMenuCreator getSwipeMenuCreator() {
        return new SwipeMenuCreator() {
            @Override
            public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
                if (viewType == TYPE_GOOD) {
                    SwipeMenuItem delItem = new SwipeMenuItem(mActivity).setBackgroundColor(getResources().getColor(R.color.color_f91c4c))
                            .setText(getString(R.string.modify_delete))
                            .setTextColor(Color.WHITE)
                            .setWidth(getResources().getDimensionPixelSize(R.dimen.size70));
                    swipeRightMenu.addMenuItem(delItem);
                }
            }
        };
    }

    @Override
    public void onLeftSwipeMenuClick(int adapterPosition, int menuPosition) {

    }

    @Override
    public void onRightSwipeMenuClick(int adapterPosition, int menuPosition) {
        showDelDialog(adapterPosition);
    }


    /**
     * 删除提示框
     *
     * @param adapterPosition adapter index
     */
    private void showDelDialog(final int adapterPosition) {
        if (mDelDialog == null) {
            mDelDialog = CommonDialog.createTwoButton(getString(R.string.sure_del_goods));
        }
        mDelDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                mDelDialog.dismiss();
            }

            @Override
            public void right() {
                delCartGood(adapterPosition);
                mDelDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        mDelDialog.show(getFragmentManager(), "delete");
    }

    @Override
    public void onRefresh() {
        setAdapterNumClickable();
        mCurPage = 1;
        mIsPullToRefresh = true;
        loadDataList(mCurPage, true);
    }

    @Override
    public void onLoadMore() {
    }

    @Override
    public void loadDataList(int curPage, boolean isPullToRefresh) {
        if (!Utils.isUserLogin(false)) {
            setEmpty();
            return;
        }
        long userId = Utils.getUserLoginInfo().getUserId();
        long supplierId = Utils.getSupplierId();
        ShoppingCartApi.getShoppingCart(mActivity, userId, supplierId, new RefreshAndLoadCallback<List<ShoppingCartGood>>(//1069,1237,1238
                isPullToRefresh) {
            @Override
            public void errorLeftOrEmptyBtnClick(View view) {
                TextView tv = (TextView) view;
                if (tv.getText().toString().equals(emptyBtnText())) {
                    switchToHome();
                } else {
                    loadDataList(mCurPage, false);
                }
            }

            @Override
            public void onResultSuccess(List<ShoppingCartGood> shoppingCartGoods, @Nullable Response response, LoadingViewCallback callback) {
                CLog.d("onResultSuccess");
                setShoppingCartCount(Utils.getShoppingCartNum(shoppingCartGoods));
                getRecordGoodId();
                mCallback = callback;
                clearList();
                if (shoppingCartGoods != null && shoppingCartGoods.size() > 0) {
                    //整理数据，帅选可购买，下架，删除，库存为0
                    sortData(shoppingCartGoods);
                    setBottomViewVisible(true);
                } else {
                    setData();
                    setBottomViewVisible(false);
                }
            }

            @Override
            public Drawable emptyDrawable() {
                return getResources().getDrawable(R.drawable.empty_shoppingcart);
            }

            @Override
            public String emptyContent() {
                return getString(R.string.empty_hint);
            }

            @Override
            public boolean showEmptyButton() {
                return true;
            }

            @Override
            public String emptyBtnText() {
                return getString(R.string.empty_go);
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                if (mListData.size() == 0) {
                    setShoppingCartCount(0);
                    setBottomViewVisible(false);
                }
            }
        });
    }

    private void clearList() {
        mListDataFix.clear();
        mUseList.clear();
        mUnUsedList.clear();
        mListData.clear();
        mCheckList.clear();
    }

    /**
     * 设置底部价格信息栏的显示状态
     *
     * @param visible true 显示
     */
    private void setBottomViewVisible(boolean visible) {
        if (visible) {
            mBottomView.setVisibility(View.VISIBLE);
            mBottomLine.setVisibility(View.VISIBLE);
        } else {
            mBottomView.setVisibility(View.GONE);
            mBottomLine.setVisibility(View.GONE);
        }
    }

    /**
     * 跳到首页
     */
    private void switchToHome() {
        if (!(mActivity instanceof MainActivity)) {//不是当前首页的购物车，则finish
            mActivity.finish();
            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY));
        }
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SWITCH_TO_HOME));
    }

    /**
     * 设置购车数量
     *
     * @param count 数量
     */
    private void setShoppingCartCount(int count) {
        cartCount = count;
        EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_SET_SHOPPINGCART_NUM, cartCount));
    }

    /**
     * 没有登录设置空
     */
    private void setEmpty() {
        setBottomViewVisible(false);
        setShoppingCartCount(0);
        mStateTypeLayout.showEmpty(getResources().getDrawable(R.drawable.empty_shoppingcart), null, getString(R.string.empty_hint)
                , getString(R.string.empty_go), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switchToHome();
                    }
                });
    }

    /**
     * 验证订单详细说明
     */
    private void validateOrder() {
        ArrayList<String> list = Utils.getJointParams(mCheckList);//获取拼接参数的结合
        String activityJSON = Utils.getActivityJSONArray(mActivityGoodsArray);
        OrderApi.validateOrder(mActivity, Utils.getUserLoginInfo().getUserId(), list.get(0), list.get(1), list.get(2), activityJSON, new DialogCallback<ValidateOrder>(mActivity) {
            @Override
            public void onSuccess(ValidateOrder validateOrder, Call call, Response response) {
                Utils.setGoodAmountPrice(mCheckList, validateOrder.getOrderItem());
                for (ShoppingCartGood good : mCheckList) {
                    i("hcy", "good amount=" + good.getAmountPrice());
                    i("hcy", "good orderAllotPrice =" + good.getOrderAllotPrice());
                }
                startPayOrder(activityJSON, list, validateOrder.getActivityPrice());
            }
        });
    }


    @OnClick({R.id.tv_calculate, R.id.tv_all})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_calculate:
                if (mCheckList.size() == 0) {
                    XToastUtils.showShortToast(getString(R.string.select_good));
                    return;
                }
                //订单验证
                validateOrder();
                break;
            case R.id.tv_all:
                mCheckBox.setChecked(!mCheckBox.isChecked(), true);
                break;
        }
    }

    /**
     * 到填写订单
     */
    private void startPayOrder(String activityJSON, ArrayList<String> paramsList, double activityDiscountPrice) {
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(IntentConfig.SHOPPING_CART_SELECT_DATA, (ArrayList<? extends Parcelable>) mCheckList);//选中商品
        bundle.putStringArrayList(IntentConfig.SHOPPING_CART_PARAMS, paramsList);//参数拼接
        bundle.putString(IntentConfig.SHOPPING_CART_ACTIVITY_JSON, activityJSON);//活动json
        bundle.putDouble(IntentConfig.SHOPPING_CART_TOTAL_PRICE, calculateSelectOriginPrice());//总价格
        bundle.putDouble(IntentConfig.SHOPPING_CART_SHOP_FREE_PRICE, shopFreePrice);//店铺活动总价满包邮的价格。大于0有效
        bundle.putBoolean(IntentConfig.SHOPPING_CART_FREE_EXPRESS, mActivityDiscount.isFreeExpress);//是否有商品满足包邮活动
        bundle.putDouble(IntentConfig.SHOPPING_CART_ACTIVITY_DISCOUNT, activityDiscountPrice);//活动抵扣价格

        Utils.startActivity(mActivity, PayOrderActivity.class, bundle);
    }

    /**
     * 整理数据，找出库存为0，删，除或者已下架的商品,，设置已有选中的id为true，
     *
     * @param shoppingCartGoods
     * @return
     */
    private void sortData(List<ShoppingCartGood> shoppingCartGoods) {

        if (shoppingCartGoods != null && shoppingCartGoods.size() > 0) {
            for (int i = 0; i < shoppingCartGoods.size(); i++) {
                ShoppingCartGood goods = shoppingCartGoods.get(i);
                goods.setType(TYPE_GOOD);
                goods.setFixedPrice(goods.getPrice());
                //找出不能选中的商品，库存为0，软删除，或者已下架
                switch (goods.getGoodsType()) {
                    case 2://组合
                    case 0://spu商品
                        if (goods.getDeleteFlag() == 1) {//删除
                            shoppingCartGoods.get(i).setState(STATE_DEL);
                            mUnUsedList.add(goods);
                            continue;
                        } else {
                            if (goods.getStatusCode() == 0 || Utils.getStockNumber(goods) == 0) {//下架或者库存为0
                                goods.setState(goods.getStatusCode() == 0 ? STATE_OUT_STOCK : STATE_NOT_ENOUGH);
                                mUnUsedList.add(goods);
                                continue;
                            }
                        }
                        break;
                    case 1://sku商品
                        if (goods.getDeleteFlag() == 1) {//删除
                            shoppingCartGoods.get(i).setState(STATE_DEL);
                            mUnUsedList.add(goods);
                            continue;
                        } else {
                            if (goods.getStatusCode() == 0) {//下架
                                goods.setState(STATE_OUT_STOCK);
                                mUnUsedList.add(goods);
                                continue;
                            }
                        }
                        GoodsSKU goodsSKU = Utils.getSkuGood(goods);
                        if (goodsSKU != null) {
                            if (goodsSKU.getDeleteFlag() == 1) {//删除
                                goods.setState(STATE_DEL);
                                mUnUsedList.add(goods);
                                continue;
                            } else {
                                if (goodsSKU.getStatusCode() == 1 || Utils.getStockNumber(goods) == 0) {
                                    goods.setState(goodsSKU.getStatusCode() == 1 ? STATE_OUT_STOCK : STATE_NOT_ENOUGH);
                                    mUnUsedList.add(goods);
                                    continue;
                                }
                            }
                        }
                        break;
                }

                goods.setState(STATE_USEABLE);
                mUseList.add(shoppingCartGoods.get(i));
            }
            mListDataFix.addAll(mUseList);
            getShopIdAndCheckGood();
            //获取活动列表
            if (!CheckUtils.isEmpty(shopIds)) {
                getActivityList();
            } else {
                setData();
            }
        }

    }

    /**
     * 获取去重的所有id，选择出上次记录的选中商品
     */
    private void getShopIdAndCheckGood() {
        if (mUseList.size() == 0) {
            Utils.clearShoppingCartUnCheckId();
            return;
        }
        List<Long> idList = new ArrayList<>();//去重的店铺id
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < mUseList.size(); i++) {
            ShoppingCartGood good = mUseList.get(i);
            if (!idList.contains(good.getShopId())) {
                idList.add(good.getShopId());
                builder.append(good.getShopId()).append(",");
            }
            mUseList.get(i).setChecked(true);
            if (mUnCheckIdList.contains(Utils.getGoodId(good))) {
                mUseList.get(i).setChecked(false);
            } else {
                mCheckList.add(mUseList.get(i));
            }
        }
        shopIds = builder.toString();
    }


    /**
     * 获取活动列表
     */
    private void getActivityList() {
        if (isFirstLoad || mIsPullToRefresh && Utils.getUserLoginInfo() != null) {//第一次加载或者刷新就显示Dialog
            ActivityApi.getActivityList(mActivity, Utils.getUserLoginInfo().getUserId(), shopIds, 1, new DialogCallback<List<ShopActivityList>>(mActivity) {

                @Override
                public void onSuccess(List<ShopActivityList> shopActivityList, Call call, Response response) {
                    mActivityInfoList.clear();
                    if (shopActivityList != null && shopActivityList.size() > 0
                            && shopActivityList.get(0).getActivityList() != null && shopActivityList.get(0).getActivityList().size() > 0) {//有活动进行匹配

                        mActivityInfoList.addAll(shopActivityList.get(0).getActivityList());//目前一个运营商一个店
                        shopFreePrice = shopActivityList.get(0).getShopFreePrice();
                        matchActivity(mActivityInfoList);
                    } else {
                        setData();//显示数据
                    }
                }

                @Override
                public void onError(Call call, Response response, Exception e) {
                    super.onError(call, response, e);
                    setData();//显示数据
                }

            });
            isFirstLoad = false;
            mIsPullToRefresh = false;
            return;
        }

        ActivityApi.getActivityList(mActivity, Utils.getUserLoginInfo().getUserId(), shopIds, 1, new JsonCallback<List<ShopActivityList>>(mActivity) {

            @Override
            public void onSuccess(List<ShopActivityList> shopActivityList, Call call, Response response) {
                mActivityInfoList.clear();
                if (shopActivityList != null && shopActivityList.size() > 0
                        && shopActivityList.get(0).getActivityList() != null && shopActivityList.get(0).getActivityList().size() > 0) {//有活动进行匹配

                    mActivityInfoList.addAll(shopActivityList.get(0).getActivityList());//目前一个运营商一个店铺
                    shopFreePrice = shopActivityList.get(0).getShopFreePrice();
                    matchActivity(mActivityInfoList);
                } else {
                    setData();//显示数据
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                setData();//显示数据
            }

        });
    }

    /**
     * 更新数据
     */
    private void setData() {
        mListData.addAll(mUseList);//添加不是活动的商品
        if (mUnUsedList.size() > 0) {
            ShoppingCartGood good = new ShoppingCartGood();
            good.setType(TYPE_GOOD_UNUSEABLE);
            mListData.add(good);
            mListData.addAll(mUnUsedList);
        }
        handleRefreshListData(mCallback, mListData);
        getActivityDiscount();
        calculateSelectPrice();
        setCheckBoxState();//是否全选
    }

    /**
     * 匹配是否满足活动
     */
    private void matchActivity(List<ShopActivityInfo> specialActivityInfo) {
        addPosition = 0;
        for (ShopActivityInfo info : specialActivityInfo) {
            //                                    if (Long.parseLong(info.getEndDtm()) > System.currentTimeMillis() &&//结束时间大于当前时间
            //                                            Long.parseLong(info.getBeginDtm()) > System.currentTimeMillis()) {//开始时间大于当前时间
            //                                        parseActivityType(info);
            //                                    }
            parseActivityType(info);
        }
        if (addPosition != 0 && mUseList.size() > 0) {
            ShoppingCartGood good = new ShoppingCartGood();
            good.setType(TYPE_GOOD_ACTIVITY);
            mListData.add(addPosition, good);
        }
        setData();
    }

    /**
     * 根据活动类型匹配
     *
     * @param info 活动 1 特价 2 新人专享 3 包邮 4满减 ,
     */
    private void parseActivityType(ShopActivityInfo info) {
        switch (info.getActivityType()) {
            case SALE://特价
                BaseActivityInfo activityScale = new Gson().fromJson(info.getActivityJson(), ActivityFree.class);
                ACRecord recordScale = Utils.matchActivityGood(activityScale, SALE, mUseList);
                if (recordScale.list.size() > 0) {//有满足活动商品
                    ShoppingCartGood good = new ShoppingCartGood();
                    good.setType(TYPE_ACTIVITY_TITLE);
                    good.setActivityId(info.getActivityId());
                    good.setActivityType(SALE);
                    good.setTitle(getString(R.string.scale));
                    good.setTitleDes(info.getActivityFullName());
                    good.setMatch(true);

                    recordScale.list.add(0, good);
                    mListData.addAll(0, recordScale.list);//满足活动的重新添加到前面
                    addPosition += recordScale.list.size();
                }
                break;
            case NEW://新人专享
                BaseActivityInfo activityNew = new Gson().fromJson(info.getActivityJson(), ActivityFree.class);
                ACRecord recordNew = Utils.matchActivityGood(activityNew, NEW, mUseList);
                if (recordNew.list.size() > 0) {//有满足活动商品
                    ShoppingCartGood good = new ShoppingCartGood();
                    good.setType(TYPE_ACTIVITY_TITLE);
                    good.setActivityId(info.getActivityId());
                    good.setActivityType(NEW);
                    good.setTitle(getString(R.string.new_use));
                    good.setTitleDes(info.getActivityFullName());
                    good.setMatch(true);

                    recordNew.list.add(0, good);
                    mListData.addAll(0, recordNew.list);//满足活动的重新添加到前面
                    addPosition += recordNew.list.size();
                }
                break;
            case FREE://包邮
                ActivityFree activityFree = new Gson().fromJson(info.getActivityJson(), ActivityFree.class);
                ACRecord recordFree = Utils.matchActivityGood(activityFree, FREE, mUseList);
                if (recordFree.list.size() > 0) {
                    ShoppingCartGood good = new ShoppingCartGood();
                    good.setType(TYPE_ACTIVITY_TITLE);
                    good.setActivityId(info.getActivityId());
                    good.setActivityType(FREE);
                    good.setTitle(getString(R.string.free));
                    if (recordFree.totalPrice >= activityFree.getFullPrice()) {
                        good.setTitleDes(info.getActivityName());
                        good.setMatch(true);
                    } else {
                        double differ = NumberUtlis.sub(activityFree.getFullPrice(), recordFree.totalPrice);
                        good.setTitleDes(info.getActivityFullName() + getString(R.string.differ_of) + differ + getString(R.string.money));
                        good.setMatch(false);
                    }
                    recordFree.list.add(0, good);
                    mListData.addAll(0, recordFree.list);//满足活动的重新添加到前面
                    addPosition += recordFree.list.size();
                }
                break;
            case SUBTRACT://满减
                ActivitySubtract activitySubtract = new Gson().fromJson(info.getActivityJson(), ActivitySubtract.class);
                ACRecord recordSub = Utils.matchActivityGood(activitySubtract, SUBTRACT, mUseList);
                if (recordSub.list.size() > 0) {//有匹配商品
                    ShoppingCartGood good = new ShoppingCartGood();
                    good.setType(TYPE_ACTIVITY_TITLE);
                    good.setActivityId(info.getActivityId());
                    good.setActivityType(SUBTRACT);
                    good.setTitle(getString(R.string.subtract));
                    if (recordSub.totalPrice >= activitySubtract.getFullPrice()) {//已经满足活动
                        good.setTitleDes(info.getActivityName());
                        good.setMatch(true);
                    } else {//未满足活动
                        double differ = NumberUtlis.sub(activitySubtract.getFullPrice(), recordSub.totalPrice);
                        good.setMatch(false);
                        good.setTitleDes(info.getActivityFullName() + getString(R.string.differ_of) + differ + getString(R.string.money));
                    }
                    recordSub.list.add(0, good);
                    mListData.addAll(0, recordSub.list);//满足活动的重新添加到前面
                    addPosition += recordSub.list.size();
                }
                break;
        }
    }

    /**
     * 设置checkbox
     */
    private void setCheckBoxState() {
        boolean check = checkIsAllSelect();
        isAllSelect = check;
        mCheckBox.setChecked(check, false, false);
    }

    /**
     * 改变全部实体数据的是否选择状态
     */
    private void changeListDataSelectState() {
        mUnCheckIdList.clear();
        mCheckList.clear();
        for (int i = 0; i < mList.size(); i++) {
            ShoppingCartGood cartGoods = mList.get(i);
            if (cartGoods.getType() == TYPE_GOOD && cartGoods.getState() == STATE_USEABLE) {//商品数据,可用数据
                cartGoods.setChecked(isAllSelect);
                if (isAllSelect) {
                    mCheckList.add(cartGoods);
                } else {
                    mUnCheckIdList.add(Utils.getGoodId(cartGoods));
                }
            }
        }
        reSortData();//重新整理数据
        if (isAllSelect) {
            Utils.clearShoppingCartUnCheckId();
        } else {
            putUnCheckIdList();
        }
    }

    /**
     * 改变全选按钮状态，Adapter的item选中状态改变时调用
     *
     * @param allSelectState
     */
    public void changeAllSelectCheckBoxState(boolean allSelectState) {
        if (isAllSelect && !allSelectState) {
            adapterChangeState = true;
            isAllSelect = false;
            mCheckBox.setChecked(false, true);
        } else if (!isAllSelect && allSelectState) {
            adapterChangeState = true;
            isAllSelect = true;
            mCheckBox.setChecked(true, true);
            mUnCheckIdList.clear();
            putUnCheckIdList();
        }
    }

    /**
     * 判断是否已全部选择
     *
     * @return true 是 false否
     */
    private boolean checkIsAllSelect() {
        boolean isAllSelect = true;
        if (mListDataFix.size() == 0) {//没有有效购买商品
            return false;
        }
        for (int i = 0; i < mList.size(); i++) {
            ShoppingCartGood cartGoods = mList.get(i);
            if (cartGoods.getType() == TYPE_GOOD && cartGoods.getState() == STATE_USEABLE && !cartGoods.isChecked()) {//是有效的商品
                isAllSelect = false;
                break;
            }
        }
        return isAllSelect;
    }

    /**
     * 选中状态监听
     *
     * @param isChecked
     * @param position
     */
    @Override
    public void checkChange(boolean isChecked, int position) {
        ShoppingCartGood good = mList.get(position);
        i("hcy", "good check = " + good.isChecked());
        i("hcy", "isChecked = " + isChecked);
        long id = Utils.getGoodId(good);
        if (isChecked) {//选中
            if (!mCheckList.contains(good)) {
                mCheckList.add(good);//添加到选中List
            }
            if (mUnCheckIdList.contains(id)) {//移除id
                mUnCheckIdList.remove(id);
            }
        } else {//没有选中
            mCheckList.remove(good);//移除选中List
            if (!mUnCheckIdList.contains(id)) {//添加到未选中id List
                mUnCheckIdList.add(id);
            }
        }

        changeAllSelectCheckBoxState(checkIsAllSelect());
        putUnCheckIdList();
        if (good.isActivity()) {//是活动商品，重新匹配
            ThreadPool.postOnUiDelayed(new Runnable() {
                @Override
                public void run() {
                    reSortData();
                }
            }, 730);//延迟，防止动画叠加
        } else {
            //活动价格
            getActivityDiscount();
            //计算总价
            calculateSelectPrice();
        }
    }

    /**
     * 增加购买数量
     *
     * @param num
     * @param pos
     */
    @Override
    public void add(int num, int pos) {
        addAction(num, pos);//先判断是否有type：1,2弹出提示框
    }

    /**
     * 减少购买数量
     *
     * @param num
     * @param pos
     */
    @Override
    public void subtract(int num, int currCount, int pos) {
        if (currCount == 1) {//弹出删除提示框
            setAdapterNumClickable();
            showDelDialog(pos);
        } else {
            setShoppingCartRequest(num, pos, 2, true);
        }
    }

    /**
     * 设置购物车数量
     *
     * @param num  数量
     * @param pos  list position
     * @param type 1，加 2，减
     */
    private void setShoppingCartRequest(int num, int pos, int type, boolean isShowDialog) {
        long supplierId = Utils.getSupplierId();
        if (isShowDialog) {//显示Dialog
            ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), mList.get(pos).getGoodsId(),
                    supplierId, mList.get(pos).getShopId(), Utils.getSKUId(mList.get(pos)), num, 1, new DialogCallback<GoodsStock>(mActivity) {

                        @Override
                        public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                            setAdapterNumClickable();
                            if (CheckUtils.isNull(goodsStock)) {
                                XToastUtils.showShortToast(getString(R.string.fail));
                                return;
                            }
                            if (goodsStock.getErrorCode() == GoodsStock.STOCK_NO) {
                                XToastUtils.showShortToast(getString(R.string.stock_no));
                                if (num > goodsStock.getStockNumber()) {
                                    setShoppingCartRequest(goodsStock.getStockNumber(), pos, type, false);
                                }
                                return;
                            }
                            if (type == 1) {//如果是加
                                cartCount++;
                            } else {
                                if (cartCount >= 1) {
                                    cartCount--;
                                }
                            }

                            setShoppingCartCount(cartCount);//设置购物数量
                            if (mList.get(pos).isActivity()) {//是活动中商品，数量改变需要重新计算是否满足活动
                                doAddSubtractResult(num, pos, type);
                            } else {//改变的不是活动中的商品，不需要重新筛选计算
                                mList.get(pos).setNumber(num);
                                notifyDataChange();
                            }
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            setAdapterNumClickable();
                        }

                        @Override
                        public GoodsStock convertSuccess(Response response) throws Exception {//库存不足,要获取returnValue返回的存库数量，重新设置购买数量为库存数量
                            return Utils.parseShopGoodCountJson(response, mActivity);
                        }
                    });
        } else {
            ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), mList.get(pos).getGoodsId(),
                    supplierId, mList.get(pos).getShopId(), Utils.getSKUId(mList.get(pos)), num, 1, new JsonCallback<GoodsStock>(mActivity) {

                        @Override
                        public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                            setAdapterNumClickable();
                            if (CheckUtils.isNull(goodsStock)) {
                                XToastUtils.showShortToast(getString(R.string.fail));
                                return;
                            }
                            if (goodsStock.getErrorCode() == GoodsStock.STOCK_NO) {
                                XToastUtils.showShortToast(getString(R.string.stock_no));
                                if (num > goodsStock.getStockNumber()) {
                                    setShoppingCartRequest(goodsStock.getStockNumber(), pos, type, false);
                                }
                                return;
                            }
                            onRefresh();
                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            setAdapterNumClickable();
                        }

                        @Override
                        public GoodsStock convertSuccess(Response response) throws Exception {//库存不足,要获取returnValue返回的存库数量，重新设置购买数量为库存数量
                            return Utils.parseShopGoodCountJson(response, mActivity);
                        }
                    });
        }

    }

    /**
     * 重新计算价格，刷新adapter
     */
    private void notifyDataChange() {
        if (mShoppingCartAdapter != null)
            mShoppingCartAdapter.notifyDataSetChanged();
        getActivityDiscount();
        calculateSelectPrice();
    }

    /**
     * 增加数量逻辑，是否是活动为1,2,4(新人专享，特价，满减)大于限购数量，大于弹出提示框
     */
    private void addAction(int num, int pos) {
        int type = mList.get(pos).getActivityType();
        if (type == SALE || type == NEW || type == SUBTRACT) {
            if (mList.get(pos).getNumber() == mList.get(pos).getLimitCount()) {//已经满足，购买数量等于限购数量
                showHintDialog(num, pos, 1);//弹出提示框
            } else {
                setShoppingCartRequest(num, pos, 1, true);
            }
        } else {
            setShoppingCartRequest(num, pos, 1, true);
        }
    }

    /**
     * 减少数量逻辑，
     */
    private void doAddSubtractResult(int num, int pos, int type) {
        int activityType = mList.get(pos).getActivityType();

        if (activityType == SALE || activityType == NEW) {
            if (type == 1) {//加
                if (mList.get(pos).getNumber() == mList.get(pos).getLimitCount() || mList.get(pos).getLimitCount() == 0) {//已经满足，购买数量等于限购数量
                    mList.get(pos).setNumber(num);
                    reSortData();//重新整理数据
                } else {
                    mList.get(pos).setNumber(num);
                    notifyDataChange();
                }
            } else {//减
                mList.get(pos).setNumber(num);
                if (num == mList.get(pos).getLimitCount() || mList.get(pos).getLimitCount() == 0) {//已经满足，购买数量等于限购数量
                    reSortData();//重新整理数据
                } else {
                    notifyDataChange();
                }
            }

        }
        //满减
        else if (activityType == SUBTRACT) {
            mList.get(pos).setNumber(num);
            reSortData();//重新整理数据
        } else {//满包邮
            mList.get(pos).setNumber(num);
            reSortData();
        }
    }

    /**
     * 弹出限购提示框
     */
    private void showHintDialog(int num, int pos, int type) {
        int count = mList.get(pos).getLimitCount();
        int acType = mList.get(pos).getActivityType();
        String content = acType == SALE ? String.format(getString(R.string.sure_add_goods_sale), count) : String.format(getString(R.string.sure_add_goods), count);
        CommonDialog addDialog = CommonDialog.createTwoButton(content);
        addDialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                setAdapterNumClickable();
                addDialog.dismiss();
            }

            @Override
            public void right() {
                setShoppingCartRequest(num, pos, type, true);
                addDialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });

        addDialog.show(getFragmentManager(), "add");
    }

    /**
     * 重新计算匹配数据
     */
    private void reSortData() {
        mUseList.clear();
        mUseList.addAll(mListDataFix);
        mListData.clear();
        matchActivity(mActivityInfoList);
    }

    /**
     * 将增加减少购买数量变为可点击
     */
    private void setAdapterNumClickable() {
        if (mShoppingCartAdapter != null) {
            mShoppingCartAdapter.setNumClickable(true);
        }
    }

    /**
     * 计算活动抵扣价格
     */
    private void getActivityDiscount() {
        mActivityGoodsArray.clear();
        //获取选中商品满足活动的集合
        if (mActivityInfoList.size() > 0) {
            mActivityGoodsArray = Utils.getCheckGoodMatchActivity(mCheckList, mActivityInfoList);
        }
        //计算活动抵扣价格
        mActivityDiscount = Utils.getActivityDisCountPrice(mActivityGoodsArray);
        StringBuilder stringBuilder = new StringBuilder(getString(R.string.activity_discount));
        stringBuilder.append(mActivityDiscount.discountPrice).append(getString(R.string.money));
        mCouponPriceTv.setText(stringBuilder);
        i("hcy", "优惠=" + stringBuilder);
    }

    /**
     * 计算选中商品总价格
     */
    private void calculateSelectPrice() {
        double totalPrice = 0.0;

        //有满减商品限购的总价
        double totalType4Limit = 0.0;

        //有满减商品的总价
        double totalType4Price = 0.0;

        //满减的价格
        double cutFullPrice = 0.0;
        //满减的减价格
        double cutPrice = 0.0;
        for (ShoppingCartGood goods : mCheckList) {
            i("hcy", "总价item=" + Utils.getGoodPrice(goods));
            if (goods.getActivityType() == 1 || goods.getActivityType() == 2) {
                if (goods.getNumber() <= goods.getLimitCount() || goods.getLimitCount() == 0) {
                    totalPrice = Utils.calculatePrice(totalPrice, Utils.getDiscountPrice(goods), goods.getNumber());
                } else {
                    totalPrice = Utils.calculatePrice(totalPrice, Utils.getDiscountPrice(goods), goods.getLimitCount());
                    totalPrice = Utils.calculatePrice(totalPrice, Utils.getGoodPrice(goods), goods.getNumber() - goods.getLimitCount());
                }

            } else if (goods.getActivityType() == 4) {
                totalType4Price = Utils.calculatePrice(totalType4Price, Utils.getGoodPrice(goods), goods.getNumber());
                totalType4Limit = Utils.calculatePrice(totalType4Limit, Utils.getGoodPrice(goods), goods.getLimitCount());
                cutFullPrice = goods.getCutFullPrice();
                cutPrice = goods.getCutPrice();
            } else {
                totalPrice = Utils.calculatePrice(totalPrice, Utils.getGoodPrice(goods), goods.getNumber());
            }

        }

        //无限购
        if (totalType4Limit == 0) {
            //满足满减的条件
            if (totalType4Price >= cutFullPrice) {
                totalPrice = NumberUtlis.add(totalPrice, NumberUtlis.sub(totalType4Price, cutPrice));
            } else {
                totalPrice = NumberUtlis.add(totalPrice, totalType4Price);
            }
        }
        //限购
        else {
            //满足满减的条件
            if (totalType4Limit >= totalType4Price && totalType4Price >= cutFullPrice || totalType4Limit < totalType4Price && totalType4Limit >= cutFullPrice) {
                totalPrice = NumberUtlis.add(totalPrice, NumberUtlis.sub(totalType4Price, cutPrice));
            } else {
                totalPrice = NumberUtlis.add(totalPrice, totalType4Price);
            }
        }

        //        mTotalPrice = totalPrice;
        mTotalMoneyTv.setAmount(totalPrice);
        i("hcy", "------------------");
        //        i("hcy", "总价=" + mTotalPrice);
    }

    /**
     * 计算选中的没参加活动前的总价
     */
    private double calculateSelectOriginPrice() {
        double totalPrice = 0.0;
        for (ShoppingCartGood goods : mCheckList) {
            totalPrice = Utils.calculatePrice(totalPrice, Utils.getGoodPrice(goods), goods.getNumber());
        }
        return totalPrice;
    }

    /**
     * 删除商品
     *
     * @param pos
     */
    private void delCartGood(int pos) {
        long goodId = Utils.getGoodId(mList.get(pos));
        long supplierId = Utils.getSupplierId();
        ShoppingCartApi.setShoppingCart(mActivity, Utils.getUserLoginInfo().getUserId(), mList.get(pos).getGoodsId(),
                supplierId, mList.get(pos).getShopId(), Utils.getSKUId(mList.get(pos)), 0, 1, new DialogCallback<GoodsStock>(mActivity) {
                    @Override
                    public void onSuccess(GoodsStock goodsStock, Call call, Response response) {
                        if (mUnCheckIdList.contains(goodId)) {//如果记录有选中的id，删除
                            mUnCheckIdList.remove(goodId);
                        }
                        XToastUtils.showShortToast(getString(R.string.address_del_success));
                        loadDataList(mCurPage, true);
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        XToastUtils.showShortToast(getString(R.string.address_del_fail));
                    }
                });

    }

    /**
     * 辅助满足活动商品匹配计算类
     */
    public static class ACRecord {
        public double totalPrice = 0.0;
        public List<ShoppingCartGood> list;
    }

    /**
     * 活动抵扣辅助类
     */
    public static class ActivityDiscount {
        public double discountPrice = 0.00;//抵扣价格
        public boolean isFreeExpress = false;//是否满足满包邮
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_OUT_LOGIN://退出
                clearList();
                mList.clear();
                notifyDataChange();
                if (mActivity instanceof MainActivity)
                    ((MainActivity) mActivity).setShoppingCartNum(0);
                setEmpty();
                break;

            case LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART://加入购物车

                //                if (mShoppingCartAdapter != null) {
                //                    if (mList.size() == 0) {
                //                        loadDataList(1, false);
                //                    } else {
                //                        loadDataList(1, true);
                //                    }
                //                } else {
                if (mActivity instanceof MainActivity)
                    ((MainActivity) mActivity).setShoppingCartNum(++LeYaoGoApplication.SHOPPING_CART_NUM);
                //                }
                break;
            case LeEventCode.MSG_CODE_REFRESH_SHOPPINGCART://商品详情添加到购物车
            case LeEventCode.MSG_CODE_ADD_ORDER:
                if (mShoppingCartAdapter != null) {
                    if (mList.size() == 0) {
                        loadDataList(1, false);
                    } else {
                        loadDataList(1, true);
                    }
                }
                break;
            case LeEventCode.MSG_CODE_SELECT_OPERATOR:
                LeYaoGoApplication.HAS_GOT_SHOPPING_CART_NUM = false;
                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_GET_SHOPPING_CART_NUM));
                break;
            //            case LeEventCode.MSG_CODE_ADD_TO_SHOPPING_CART://加入购物车
            //                if (mActivity instanceof MainActivity)
            //                    ((MainActivity) mActivity).setShoppingCartNum(++LeYaoGoApplication.SHOPPING_CART_NUM);
            //                break;

            case LeEventCode.MSG_CODE_FINISH_GOODS_ACTIVITY://从分组进入购物车,进入特价,进入购物车,删除购物车商品,点击去逛逛,finish掉该页面
                if (!(mActivity instanceof MainActivity)) {
                    mActivity.finish();
                }
                break;
        }
    }

    private boolean isFirstSwitch = true;//是否第一次点击切换（如果是懒加载，第一次切换到购物车不需要加载）

    /**
     * 加载数据
     */
    public void loadData() {

        if (isFirstSwitch && !isShowBack) {
            isFirstSwitch = false;
            return;
        }
        if (mList.size() == 0) {
            loadDataList(1, false);
        } else {
            loadDataList(1, true);
        }
    }

    @Override
    public void leftContainerClick() {
        if (getArguments().getBoolean("showBack", false)) {
            super.leftContainerClick();
        }
    }

    /**
     * 异步存未选中的商品id
     */
    private void putUnCheckIdList() {
        AsyncTaskUtils.exe(new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Utils.putShoppingCartUnCheckId(mUnCheckIdList);
                return null;
            }
        });
    }
}

